<template>
  <div @click="ClickTitle" class="codePage">
    <el-dialog width="400px" :visible.sync="dialogVisible" title="回到登录">
      <div class="codePage-img">
        <div><img src="../../static/images/login01.png" alt="" /></div>

        <div class="codePage-img-span">
          <span>为了你的信息安全我们会给你发送验证码</span>
        </div>
      </div>
      <div class="codePage-btn">
        <el-input
          v-model="code"
          placeholder="请输入验证码"
          style="width: 180px; padding-right: 10px; padding-bottom: 20px"
        ></el-input>
        <el-button type="danger" :disabled="isTrue" @click="setCode"
          >重新获取 <span>{{ count }}</span></el-button
        >
      </div>
      <div class="codePage-btn-bottom">
        <el-button type="danger" style="width: 293px" @click="goLogin"
          >下一步</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "CodePage",
  data() {
    return {
      dialogVisible: true,
      code: "", //收集验证码
      isTrue: true, //用于控制按钮的使用
      count: 10,
      phone: "",
    };
  },
  methods: {
    ClickTitle(e) {
      if (e.target.textContent === "回到登录") {
        this.$router.history.push("/login");
      }
    },
    async setCode() {
      //点击按钮发送验证码
      let { phone } = this;
       await this.$API.register.getCode(phone);
      this.isTrue = false;
      let timer = setInterval(() => {
        this.count--;
        if (this.count === 0) {
          this.isTrue = false; //按钮高亮
          this.count = 60;
          clearInterval(timer);
        }
      }, 1000);
    },
    async goLogin() {
      try {
        //验证验证码是否正确
        let { phone, code } = this;
        await this.$API.register.isCodeMa(phone, code);
        //验证如果成功则发起注册
        let password = "123456789ydq";
        let nickname = "binary1345";
        let captcha = code;
        //发起注册
        await this.$API.register.reqRegister(
          phone,
          password,
          captcha,
          nickname
        );
        //注册成功跳转到登录页面
        this.$router.history.push("/login");
      } catch (e) {
        this.$message.error("验证码错误，请重新输入");
      }
    },
  },
  async mounted() {
    console.log("params:", this.$route.params);
    this.phone = this.$route.params.phone;
    //自动发送一次验证码
    let { phone } = this;
     await this.$API.register.getCode(phone);
    // console.log(code);//验证码是存放在手机上的，这里看不到，打印了200说明手机拿到验证码了
    //控制发送验证码的时间
    let timer = setInterval(() => {
      this.count--;
      if (this.count === 0) {
        this.isTrue = false; //按钮高亮
        this.count = 60;
        clearInterval(timer);
      }
    }, 1000);
  },
};
</script>

<style scoped>
.codePage-img {
  text-align: center;
}
.codePage-img-span {
  margin-top: 20px;
  margin-bottom: 40px;
}
.codePage-btn {
  text-align: center;
}
.codePage-btn-bottom {
  text-align: center;
}
</style>